package com.example.trans.controller;

import com.example.trans.service.LogInfoService;
import com.example.trans.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/user2")
public class UserInfoController2 {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private LogInfoService logInfoService;

    // @Transactional 自动实现事务的开启，提交或者回滚
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
    @RequestMapping("/register")
    public Boolean register(String userName, String password) throws IOException {
        // 1. 参数校验
        log.info("/user/register接收到参数：userName: {}, password: {}", userName, password);
        if(!StringUtils.hasLength("userName") || !StringUtils.hasLength(password)){
            return false;
        }
        // 2. 调用 service
        try{
            Integer result = userInfoService.insertUserInfo(userName, password);
            Integer result2 = logInfoService.insertLogInfo(userName, "用户注册");

            if(result <= 0 || result2 <= 0){
                return false;
            }
        }catch (Exception e){
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return true;
    }
}
